package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.KbAdvertAddChannelRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.qf.config.AlipayConfig;
import com.qf.pojo.*;
import com.qf.service.OrderService;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.utils.UUIDUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 订单的后端访问地址
 */
@WebServlet("/order")
public class OrderServlet extends BaseServlet {
    /**
     * 产生订单的方法
     * @param request
     * @param response
     */
    public void generOrder(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        //1)如果当前request对象获取HttpSession没有"user"信息,重定向到登录
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){
            //重定向到登录
            response.sendRedirect(request.getContextPath()+"/jsp/login.jsp");
            return;
        }

        //2)封装订单数据
        Order order = new Order() ;
        //订单编号
        order.setOid(UUIDUtils.getId()) ;
        //下单时间
        order.setOrdertime(new Date()) ;
        //总金额 --->来自于购物车 ---HttpSession中获取
        Cart cart = (Cart) session.getAttribute("cart");
        order.setTotal(cart.getTotalMoney()) ;

        //封装订单项列表数据
        OrderItem orderItem = null ;

        //订单项里面的数据:商品实体/小计/数量都来自于购物车项
        for( CartItem cartItem:cart.getCartItems()){
            orderItem = new OrderItem() ;
            //订单项编号:uuid生成
            orderItem.setItemid(UUIDUtils.getId()) ;
            //商品实体
            orderItem.setProduct(cartItem.getProduct());
            //商品数量
            orderItem.setCount(cartItem.getCount());
            //小计
            orderItem.setSubtotal(cartItem.getSubMoney());
            //这个订单项属于哪个订单
            orderItem.setOrder(order) ;

            //订单中包含的多个订单项---
            List<OrderItem> list = order.getItems();
            list.add(orderItem) ;
        }

        //订单所属的用户
        order.setUser(user);

        //3)调用业务接口
        OrderService orderService = new OrderServiceImpl() ;
        orderService.addOrder(order) ;


        //4)将订单数据存储在request域中
        request.setAttribute("order",order);
        //将HttpSession的购物车删除
        session.removeAttribute("cart") ;
        //请求转发到订单详情
        request.getRequestDispatcher("/jsp/order_info.jsp").forward(request,response);

    }

    /**
     * 前台_订单分页获取
     * @param request 请求对象
     * @param response 响应对象
     */
    public void getOrderByPage(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        String curPage = request.getParameter("curPage");
        String pSize = request.getParameter("pSize");
        if(curPage==null || "".equals(curPage)){
            curPage = "1" ; //当前页码
        }
        if(pSize==null || "".equals(pSize)){
            pSize = "3" ; //每页显示的条数
        }
        int currentPage = Integer.parseInt(curPage) ;
        int pageSize = Integer.parseInt(pSize) ;

        //从request对象中获取HttpSession
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            //完成登录
            //重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/jsp/login.jsp");
            return;
        }
        //调用订单的业务接口
        OrderService orderService = new OrderServiceImpl() ;
        PageBean<Order>  pb  = orderService.getOrderByPage(user.getUid(),currentPage,pageSize ) ;
        if(pb!=null){
            request.setAttribute("pb",pb);
        }
        //请求转发到订单列表
        request.getRequestDispatcher("/jsp/order_list.jsp").forward(request,response);
    }

    /**
     * 通过订单编号获取订单详情信息
     * @param request 请求
     * @param response 响应
     */
    public void getOrderById(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //${pageContext.request.contextPath}/order?methodName=getOrderById&oid=${o.oid}
        //接收订单编号
        String oid = request.getParameter("oid") ;
        //调用订单业务接口获取订单实体
        OrderService orderService = new OrderServiceImpl() ;
        Order order = orderService.getOrder(oid) ;
        if(order!=null){
            //存储在request域中
            request.setAttribute("order",order);
        }
        //请求转发到订单详情页
        request.getRequestDispatcher("/jsp/order_info.jsp").forward(request,response);

    }

    /**
     * 订单支付
     * @param request 请求
     * @param response 响应
     */
    public void pay(HttpServletRequest request,HttpServletResponse response) {

        //获取订单编号---->通过订单编号获取订单实体
        String oid = request.getParameter("oid");
        System.out.println("获取到的订单编号是:"+oid) ;
        //通过订单业务接口获取订单实体
        OrderService orderService = new OrderServiceImpl() ;
        Order order = orderService.getOrder(oid);
        System.out.println("订单金额是:"+order.getTotal());

        //支付宝 sdk--->项目中关联支付宝的sdk
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(
                     AlipayConfig.gatewayUrl, // 支付宝网关地址
                     AlipayConfig.app_id,     //自己的appid
                     AlipayConfig.private_key,   //个人私钥
                     "json",         //json数据
                     AlipayConfig.charset,  //字符编码格式
                     AlipayConfig.alipay_public_key,  //支付宝公钥
                     AlipayConfig.sign_type
            );//验签方式RSA2

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url); //同步回调
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url); //异步回调



           /* JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", order.getOid());
            bizContent.put("total_amount", order.getTotal());
            bizContent.put("subject", "测试商品");
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            alipayRequest.setBizContent(bizContent.toString());*/

            //支付宝请求对象：设置订单相关的数据
           alipayRequest.setBizContent("{\"out_trade_no\":\""+ order.getOid() +"\","  //订单编号
                    + "\"total_amount\":\""+ order.getTotal() +"\","                       //订单总金额
                    + "\"subject\":\""+"subject"+"\","                           //支付的主题名称
                    + "\"body\":\""+ "product" +"\","                                 //设置商品的描述信息,(可以为空)
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


           //必须设置响应的乱码
            response.setContentType("text/html;charset=UTF-8") ;



            //支付宝响应对象
            //将设置表单信息全部以form表单方式发送支付宝
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            //获取结果集(配置类所有appid/支付宝公钥/私钥/所有订单相关的参数) ---支付宝登录页面
            response.getWriter().write(result); //支付宝网关将支付宝的登录页面响应给浏览器
            System.out.println(result); //打印控制台
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

    }
}
